<template>
  <view class="page page-activity-form ui-form-basic">
    <page-header :showPlaceHolder="false" :customTitle="customTitle"></page-header>
    <fui-form ref="formRef" :model="form" class="form-wrapper grey" labelWidth="200" labelSize="28" labelWeight="bold" :top="store.getters.topHeight">
      <view class="form-block-title">基本信息</view>
      <view class="form-block">
        <fui-form-item :bottomBorder="false" label="活动封面" prop="cover" :padding="['16rpx', 0]">
          <template #vertical>
            <upload-image class="form-upload" @uploaded="uploadedCover" :defaultList="form.cover ? [form.cover] : []"></upload-image>
          </template>
        </fui-form-item>
        <fui-form-item label="活动名称" prop="name" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" maxlength="20" :padding="[0]" :borderBottom="false" placeholder="请输入活动名称" v-model="form.name"></fui-input>
        </fui-form-item>
        <fui-form-item label="报名开始时间" prop="startApplyTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('startApplyTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择报名开始时间" v-model="form.startApplyTimeText" disabled :color="isStartApply ? '#999' : '#333'"></fui-input>
        </fui-form-item>
        <fui-form-item label="报名结束时间" prop="endApplyTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('endApplyTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择报名结束时间" v-model="form.endApplyTimeText" disabled></fui-input>
        </fui-form-item>
        <fui-form-item label="活动开始时间" prop="startActivityTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('startActivityTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择活动开始时间" v-model="form.startActivityTimeText" disabled></fui-input>
        </fui-form-item>
        <fui-form-item label="活动结束时间" prop="endActivityTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('endActivityTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择活动结束时间" v-model="form.endActivityTimeText" disabled></fui-input>
        </fui-form-item>
        <fui-form-item label="活动描述" prop="description" left="0" marginTop="14" :padding="['16rpx', 0]">
          <template v-slot:vertical>
            <fui-textarea size="28" maxlength="500" height="64rpx" :isCounter="true" radius="16" borderColor="#DFDFDF" v-model="form.description" placeholder="请输入活动描述" textareaBorder></fui-textarea>
          </template>
        </fui-form-item>
      </view>
      <view class="form-block-title">优惠设置</view>
      <view class="form-block">
        <fui-form-item :bottomBorder="false" label="优惠类型" prop="discountType"
          labelWeight="600" :left="0" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box">
            <view class="cycle" :class="{'cycle-active': form.discountType == item.code}"
              v-for="item in ACTIVITY_DISCOUNT_TYPE" :key="item.code" @click="handleChangeDiscountType(item.code)">
              <image v-if="form.discountType == item.code" class="cycleimg"
                src="../../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
        </fui-form-item>
        <view class="form-block-title">满减门槛及优惠<fui-text :text="`(${discountList.length}/5)`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text></view>
        <view class="discount-list">
          <view class="discount-item" :class="{'is-shake': showError && item.validType}" v-for="(item, index) in discountList" :key="index">
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].aLabel" size="24"></fui-text>
            <fui-form-item label="" prop="startNum" left="0" :padding="['16rpx', 0]">
              <fui-input v-model="item.startNum" :disabled="isStartApply" type="number" placeholder="满减门槛" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" @input="onChangeStartNum($event, index)"></fui-input>
            </fui-form-item>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].aUnit" size="24"></fui-text>
            <fui-text text="，" size="24"></fui-text>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].bLabel" size="24"></fui-text>
            <fui-form-item label="" prop="discountNum" left="0" :padding="['16rpx', 0]">
              <fui-input v-model="item.discountNum" :disabled="isStartApply" type="digit" placeholder="优惠力度" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" @input="onChangeDiscountNum($event, index)"></fui-input>
            </fui-form-item>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].bUnit" size="24"></fui-text>
            <template v-if="!isStartApply">
              <fui-icon v-if="index === 0" name="plussign-fill" size="40" color="#f95a5a" @click="handleAddDiscount"></fui-icon>
              <fui-icon v-else name="minussign-fill" size="40" color="var(--fui-color-primary)" @click="handleRemoveDiscount(index)"></fui-icon>
            </template>
          </view>
        </view>
        <fui-form-item :bottomBorder="false" label="活动范围" prop="productScope"
          labelWeight="600" :left="0" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box">
            <view class="cycle" :class="{'cycle-active': form.productScope == item.code}"
              v-for="item in ACTIVITY_GOODS_RANGE" :key="item.code" @click="handleChangeGoodsRange(item.code)">
              <image v-if="form.productScope == item.code" class="cycleimg"
                src="../../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
          <fui-text text="活动创建后，活动范围将无法修改。" :padding="['16rpx', 0]" size="24" color="#999"></fui-text>
        </fui-form-item>
        <view class="form-block-title" v-if="form.productScope === 42">
          已选品类<fui-text :text="`(${checkedCategoryIds.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text text="选择品类" size="24" color="var(--fui-color-primary)" @click="onShowCategoryPicker"></fui-text>
          </view>
        </view>
        <view class="form-block-title" v-if="form.productScope === 43">
          已选供应商<fui-text :text="`(${checkedSupplierIds.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text text="选择供应商" size="24" color="var(--fui-color-primary)" @click="handleManageSullier"></fui-text>
          </view>
        </view>
      </view>
    </fui-form>

    <view class="btn-wrapper ui-fixed-footer">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
      <fui-button text="保存" height="78rpx" radius="8rpx" :margin="['0']" :disabled="isLoading" @click="handleSubmit"></fui-button>
    </view>

    <!-- 时间 -->
    <fui-date-picker :show="onShowDatePicker" type="5" :value="defaultDateTime" @change="onChangeDate" @cancel="onCancelDate"></fui-date-picker>

    <!-- 选择运营品类 -->
    <multilevel-picker ref="categoryPickerRef" :maxLevel="1" :data="categoryData" :cacheData="categoryCacheData"
      @submit="submitCategory" :defaultProps="categoryProps"></multilevel-picker>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { getObjectWithValues } from '@/utils/tools'
import utils from '@/components/firstui/fui-utils'
import { ACTIVITY_DISCOUNT_TYPE, ACTIVITY_GOODS_RANGE, ACTIVITY_VALID_MESSAGE } from './consts'
import pageHeader from '@/components/header'
import uploadImage from '@/components/upload/image'
import multilevelPicker from '@/components/multilevel'
import activityApi from '@/api/activity/supply'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const customTitle = ref('新增活动')
const activityId = ref('')
onLoad((option) => {
  categoryData.value = store.getters.productCategoryFormatting
  if (option.activityId) {
    customTitle.value = '编辑活动'
    activityId.value = option.activityId
    getActivityDetail()
  }
})

const formRef = ref(null)
const form = ref({
  discountType: 21
})
const rules = [
  {
    name: 'cover',
    rule: ['required'],
    msg: ['请上传活动封面']
  },
  {
    name: 'name',
    rule: ['required'],
    msg: ['请输入活动名称']
  },
  {
    name: 'startActivityTimeText',
    rule: ['required'],
    msg: ['请选择活动开始时间']
  },
  {
    name: 'endActivityTimeText',
    rule: ['required'],
    msg: ['请选择活动结束时间']
  },
  {
    name: 'startApplyTimeText',
    rule: ['required'],
    msg: ['请选择报名开始时间']
  },
  {
    name: 'endApplyTimeText',
    rule: ['required'],
    msg: ['请选择报名结束时间']
  },
  {
    name: 'productScope',
    rule: ['required'],
    msg: ['请选择活动范围']
  }
]

const uploadedCover = (e) => {
  form.value.cover = e[0]
}
const handleChangeDiscountType = (code) => {
  if (activityId.value) {
    modal.msgError('优惠类型不允许修改！')
    return
  }
  form.value.discountType = code
  discountList.value = [{}]
}
const handleChangeGoodsRange = async (productScope) => {
  if (activityId.value) {
    modal.msgError('活动范围不允许修改！')
    return
  }
  form.value.productScope = productScope
  checkedCategoryIds.value = []
  checkedSupplierIds.value = []
  store.commit('SET_ACTIVITY_SUPPLIER', [])
}

// 活动时间
const defaultDateTime = utils.dateFormatter(new Date(), 'y-m-d h:i', 4)
const onShowDatePicker = ref(false)
const curDateFiled = ref('')
const isStartApply = computed(() => { // 活动报名开始状态
  const nowTime = new Date().getTime()
  return form.value.oldApplyStartTime && nowTime >= form.value.oldApplyStartTime
})
const handleShowDatePicker = (field) => {
  if (field === 'startApplyTimeText' && isStartApply.value) {
    return
  }
  curDateFiled.value = field
  onShowDatePicker.value = true
}
const onChangeDate = (e) => {
  form.value[curDateFiled.value] = e ? `${e.year}/${e.month}/${e.day} ${e.hour}:${e.minute}` : ''
  onShowDatePicker.value = false
}
const onCancelDate = () => {
  onShowDatePicker.value = false
}

// 指定品类
const checkedCategoryIds = ref([])
const categoryData = ref([])
const categoryPickerRef = ref(null)
const categoryProps = {
	text: 'name',
	value: 'id',
	children: 'children'
}
const categoryCacheData = ref([])
const onShowCategoryPicker = () => {
	categoryPickerRef.value.show()
}
const submitCategory = (res) => {
  categoryCacheData.value = res.cacheData
  checkedCategoryIds.value = res.data.map(item => item.value)
}

// 指定供应商
const checkedSupplierIds = ref([])
const handleManageSullier = () => {
  tab.navigateTo(`/pages/activity/supply/selectSupplier?activityId=${activityId.value}&isStartApply=${isStartApply.value ? '1' : '0'}`)
}
onShow(() => {
  if (form.value.productScope == 43) {
    checkedSupplierIds.value = store.getters.activitySupplier
  }
})

onBackPress(() => {
  store.commit('SET_ACTIVITY_SUPPLIER', [])
  store.commit('SET_ACTIVITY_OLDSUPPLIER', [])
})

// 满减门槛及优惠设置
const discountList = ref([{}])
const onChangeStartNum = async (value, index) => {
  if (value <= 0) {
    modal.msgError('满减门槛必须大于0！')
    discountList.value[index].startNum = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('满减门槛必须为整数！')
    discountList.value[index].startNum = await ''
  }
  showError.value = false
}
const onChangeDiscountNum = async (value, index) => {
  if (value <= 0) {
    modal.msgError('优惠力度必须大于0！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 21 && value.toString().indexOf('.') > -1) {
    modal.msgError('优惠力度必须为整数！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 22 && value >= 10) {
    modal.msgError('优惠力度必须小于10！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 22 && value.toString().indexOf('.') > -1 && value.toString().split('.')[1].length > 1) {
    modal.msgError('优惠力度必须精确到1位小数！')
    discountList.value[index].discountNum = await ''
  }
  showError.value = false
}
const handleAddDiscount = () => {
  if (discountList.value.length >= 5) {
    modal.msgError('优惠力度最多支持添加5个！')
    return
  }
  discountList.value.push({})
}
const handleRemoveDiscount = (index) => {
  discountList.value.splice(index, 1)
}

// 校验满减门槛及优惠设置
const showError = ref(false)
const isNoValidDiscount = (row) => {
  let validType = ''
  if (!row.startNum || !row.discountNum) {
    validType = 'empty'
  } else if (form.value.discountType === 21 && (row.startNum - row.discountNum <= 0)) {
    validType = 'above'
  }
  return validType
}
const validatorDiscountList = () => {
  let isValid = true
  discountList.value.forEach(item => {
    item.validType = isNoValidDiscount(item)
    if (item.validType) {
      showError.value = true
      isValid = false
      modal.msgError(ACTIVITY_VALID_MESSAGE[item.validType])
      return
    } else {
      showError.value = false
      isValid = true
    }
  })
  return isValid
}

// 活动详情
const getActivityDetail = () => {
  modal.loading('加载中...')
  try{
    activityApi.getActivityDetail(activityId.value).then(res => {
      modal.closeLoading()
      if (res.code === 0 && res.data) {
        form.value = res.data
        form.value.oldApplyStartTime = form.value.applyStartTime
        form.value.startApplyTimeText = utils.dateFormatter(new Date(res.data.applyStartTime), 'y/m/d h:i', 4)
        form.value.endApplyTimeText = utils.dateFormatter(new Date(res.data.applyEndTime), 'y/m/d h:i', 4)
        form.value.startActivityTimeText = utils.dateFormatter(new Date(res.data.startTime), 'y/m/d h:i', 4)
        form.value.endActivityTimeText = utils.dateFormatter(new Date(res.data.endTime), 'y/m/d h:i', 4)
        const resList = res.data.discountRules.split(',')
        const list = resList.map(item => {
          return {
            startNum: item.split('-')[0],
            discountNum: item.split('-')[1]
          }
        })
        discountList.value = list
        
        if (form.value.productScope == 42) { // 指定分类数据回显处理
          checkedCategoryIds.value = form.value.productSpuIds.split(',')
          categoryCacheData.value = categoryData.value.map(item => {
            return {
              checked: form.value.productSpuIds.indexOf(item.id) > -1,
              isActive: false,
              isShow: true,
              level: 1,
              parent: '00',
              parentArr: ['00'],
              status: form.value.productSpuIds.indexOf(item.id) > -1 ? 'all' : 'none',
              disabled: form.value.productSpuIds.indexOf(item.id) > -1 && isStartApply.value,
              text: item.name,
              value: item.id
            }
          })
        }

        if (form.value.productScope == 43) { // 指定供应商数据回显处理
          checkedSupplierIds.value = form.value.productSpuIds.split(',')
          store.commit('SET_ACTIVITY_SUPPLIER', checkedSupplierIds.value)
          store.commit('SET_ACTIVITY_OLDSUPPLIER', checkedSupplierIds.value)
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  }catch(err){
    modal.closeLoading()
    modal.msgError(err)
  }
}

// 提交表单方法
const isLoading = ref(false)
const handleSubmit = async () => {
  const validRes = await formRef.value.validator(form.value, rules)
  if (validRes.isPassed) {
    const applyStartTime = new Date(form.value.startApplyTimeText).getTime()
    const applyEndTime = new Date(form.value.endApplyTimeText).getTime()
    const startTime = new Date(form.value.startActivityTimeText).getTime()
    const endTime = new Date(form.value.endActivityTimeText).getTime()
    if (applyEndTime <= applyStartTime) {
      modal.msgError('报名结束时间必须大于报名开始时间！')
      return
    }
    if (applyEndTime >= startTime) {
      modal.msgError('报名结束时间必须小于活动开始时间！')
      return
    }
    if (endTime <= startTime) {
      modal.msgError('活动结束时间必须大于活动开始时间！')
      return
    }
    const validList = validatorDiscountList()
    if (!validList) {
      return
    }
    if (form.value.productScope === 32 && !checkedCategoryIds.value.length) {
      modal.msgError('请至少添加一个活动品类！')
      return
    }
    if (form.value.productScope === 33 && !checkedSupplierIds.value.length) {
      modal.msgError('请至少添加一个供应商！')
      return
    }
    const discountRules = discountList.value.map(item => item.startNum + '-' + item.discountNum)
    let productSpuIds = []
    if (form.value.productScope == 42) {
      productSpuIds = checkedCategoryIds.value
    }
    if (form.value.productScope == 43) {
      productSpuIds = checkedSupplierIds.value
    }
    const formData = {
      id: form.value.id || '',
      cover: form.value.cover,
      name: form.value.name,
      startTime,
      endTime,
      applyStartTime,
      applyEndTime,
      description: form.value.description || '',
      discountType: form.value.discountType,
      discountRules: discountRules.join(','),
      productScope: form.value.productScope,
      productSpuIds: productSpuIds.join(',')
    }
    const entity = getObjectWithValues(formData)
    const apiUrl = form.value.id ? 'updateActivity' : 'addActivity'
    isLoading.value = true
    activityApi[apiUrl](entity).then((res) => {
      store.commit('SET_ACTIVITY_SUPPLIER', [])
      store.commit('SET_ACTIVITY_OLDSUPPLIER', [])
      if (res.code === 0) {
        modal.msg(`活动信息已${form.value.id ? '修改' : '添加'}！`)
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msgError(res.msg)
      }
    }).catch(err => {
      isLoading.value = false
    })
  }
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.page-activity-form {
  padding-bottom: 150rpx;

  .discount-list {
    .discount-item {
      display: flex;
      align-items: center;
      margin-top: 32rpx;
      padding: 0 10rpx;
      &.is-shake {
        border: 2rpx dashed #f95a5a;
      }
      ::v-deep .fui-text__wrap {
        .fui-text__content {
          white-space: nowrap;
        }
      }
      .fui-form__item-wrap {
        width: auto;
        border-radius: 8rpx !important;
        background-color: #f7f7f7 !important;
        margin: 0 10rpx;
        padding: 0 16rpx;
      }
      .fui-icon {
        margin-left: 24rpx;
      }
    }
  }
  ::v-deep.textarea-box .fui-form__wrap-inner {
    display: initial !important;
    padding: 0 !important;
  }

  .cycle-box {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .cycle {
      width: 160rpx;
      height: 64rpx;
      background: #F5F7FE;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      opacity: 1;
      border: 2rpx solid #E7EBFB;
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #333333;
      text-align: center;
      line-height: 64rpx;
      margin-right: 20rpx;
      position: relative;
    }

    .cycle-active {
      font-weight: bold;
      color: var(--fui-color-primary);
      border: 2rpx solid var(--fui-color-primary);
    }

    .cycleimg {
      width: 30rpx;
      height: 27rpx;
      display: block;
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>